package com.wondersgroup.core.util;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

import net.rubyeye.xmemcached.MemcachedClient;
import net.rubyeye.xmemcached.MemcachedClientBuilder;
import net.rubyeye.xmemcached.XMemcachedClientBuilder;
import net.rubyeye.xmemcached.command.BinaryCommandFactory;
import net.rubyeye.xmemcached.exception.MemcachedException;
import net.rubyeye.xmemcached.utils.AddrUtil;

public class Memcache {
	static MemcachedClient memCachedClient=null;  
    static{  
    	MemcachedClientBuilder builder = new XMemcachedClientBuilder(
    			AddrUtil.getAddresses("10.1.67.40:11211"),
    			new int[] { 1, 1, 1, 1 });
    	// 设置连接池大小，即客户端个数   
        builder.setConnectionPoolSize(50);   
  
        // 宕机报警   
        builder.setFailureMode(true);   
  
        // 使用二进制文件   
        builder.setCommandFactory(new BinaryCommandFactory()); 
        try {
			memCachedClient = builder.build();
			memCachedClient.setOpTimeout(5000L);//设置等待超时时间，单位是毫秒
		} catch (IOException e) {
			e.printStackTrace();
		}
    }  
    public static Object  get(String key)  
    {  
    	Object o = null;
        try {
			o = memCachedClient.get(key);
		} catch (TimeoutException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (MemcachedException e) {
			e.printStackTrace();
		}  
        return o;
    }  
    public static boolean set(String key,int expireTime, Object o)  
    {         
    	boolean flag = false;
        try {
			flag = memCachedClient.set(key, expireTime, o);
		} catch (TimeoutException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (MemcachedException e) {
			e.printStackTrace();
		}  
        return flag;
    }  
    public static boolean delete(String key)  
    {  
    	boolean flag = false;
        try {
        	flag = memCachedClient.delete(key);
		} catch (TimeoutException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (MemcachedException e) {
			e.printStackTrace();
		}  
        return flag;
    } 
    public static void flushAll()  
    {         
    	try {
			memCachedClient.flushAll();
		} catch (TimeoutException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (MemcachedException e) {
			e.printStackTrace();
		}
    } 
}
